package cn.edu.zjut.chopper.registry.servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import cn.edu.zjut.chopper.constant.Constant;
import cn.edu.zjut.chopper.message.RemoteInterface;
import cn.edu.zjut.chopper.name.NameServer;
import cn.edu.zjut.chopper.registry.RegistryContext;

/**
 * Servlet implementation class RemoteInterfaceMonitorView
 */
public class RemoteInterfaceMonitorView extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static Log LOG = LogFactory
			.getLog(RemoteInterfaceMonitorView.class);

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public RemoteInterfaceMonitorView() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String name = request.getParameter("Name");
		String url = request.getParameter("Url");
		String version = request.getParameter("Version");

		if (StringUtils.isEmpty(name) || StringUtils.isEmpty(url)
				|| StringUtils.isEmpty(version)) {
			getServletContext().getRequestDispatcher("/error.jsp").forward(
					request, response);
			if (LOG.isErrorEnabled()) {
				LOG.error("Name Url Version is needed for an remote interface.");
			}
			return;
		}

		NameServer nameServer = (NameServer) RegistryContext
				.get(Constant.NameServer);

		RemoteInterface ri = nameServer.find(name, version, url);

		if (ri == null || StringUtils.isEmpty(ri.getInterfaceSourceFilePath())) {
			getServletContext().getRequestDispatcher("/error.jsp").forward(
					request, response);
			if (LOG.isErrorEnabled()) {
				LOG.error("the remote interface is not bound: " + name + "|"
						+ version + "|" + url);
			}
			return;
		}

		request.setAttribute("remote_interface", ri);
		getServletContext().getRequestDispatcher(
				"/remote_interface_monitor.jsp").forward(request, response);
		return;
	}

}
